/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package nut.com.feed;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;

public class FeedWriter2 extends HttpServlet {

    final static String XHTML = "http://www.w3.org/1999/xhtml";
    static String strLink = "";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //resp.setContentType("text/pain");
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        PrintWriter pw = response.getWriter();
        String strTitle = request.getParameter("title");
        strLink = request.getParameter("link");
        String strDisc = request.getParameter("dis");

        if (strTitle.trim().isEmpty() || strLink.trim().isEmpty() || strDisc.trim().isEmpty()) {
            response.setContentType("text/html; charset=UTF-8");
            try {
                CreateRssWeb(request, response);
            } catch (Exception e) {
            }
        } else {
            Pattern pattern = Pattern.compile("(http://)[[a-z,0-9,A-Z].]*.");
            Matcher matcher = pattern.matcher(strLink);
            if (!matcher.matches()) {
                strLink = "http://" + strLink;
            }
            String value[] = {strTitle, strLink, strDisc};

            try {
                File file = new File("C:/Users/Nut/Documents/utain-lab4-parser/Utain-FeedWriter2/web/db.sh");
                //if file doesnt exists, then create it
                if (!file.exists()) {
                    file.createNewFile();
                } else {
                    //true = append file
                    BufferedWriter bufferWritter = new BufferedWriter(
                            new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8"));
                    bufferWritter.append(value[0] + "\n");
                    bufferWritter.append(value[1] + "\n");
                    bufferWritter.append(value[2] + "\n");
                    bufferWritter.append((new java.util.Date()).toString() + "\n");
                    bufferWritter.flush();
                    bufferWritter.close();
                }
                CreateRssWeb(request, response);
            } catch (Exception ex) {
                Logger.getLogger(FeedWriter2.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }
    static ArrayList<String> list;

    private void CreateRssWeb(HttpServletRequest req, HttpServletResponse res) throws Exception {
        req.setCharacterEncoding("UTF-8");
        res.setCharacterEncoding("UTF-8");
        res.setContentType("text/xml; charset=UTF-8");

        PrintWriter wt = res.getWriter();
        //read file

        FileInputStream is;
        int i = 0;
        list = new ArrayList<String>();
        //reader

        is = new FileInputStream("C:/Users/Nut/Documents/utain-lab4-parser/Utain-FeedWriter2/web/db.sh");
        //DataInputStream ds = new DataInputStream(is);
        //BufferedReader br = new BufferedReader(new InputStreamReader(ds, "UTF-8"));
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        String strLine;
        while ((strLine = br.readLine()) != null) {
            list.add(strLine);
            //System.err.println(x.get(i) + "\t" + i);
            i++;
        }
        br.close();
        //invert list
        Collections.reverse(list);

        XMLOutputFactory xof = XMLOutputFactory.newInstance();
        XMLStreamWriter xtw = xof.createXMLStreamWriter(wt);
        xtw.writeStartDocument("UTF-8", "1.0");
        //xtw.setDefaultNamespace(XHTML);
        // xtw.setPrefix("xsi", XHTML);
        xtw.writeStartElement("rss");
        xtw.writeAttribute("version", "2.0");
        {
            xtw.writeStartElement("channel");
            {
                xtw.writeStartElement("title");
                xtw.writeCharacters("XML Feed Writer Version 2");
                xtw.writeEndElement();

                xtw.writeStartElement("link");
                xtw.writeCharacters("http://www.kku.ac.th/");
                xtw.writeEndElement();

                xtw.writeStartElement("description");
                xtw.writeCharacters("Khone kean University Information News RSS Feed");
                xtw.writeEndElement();

                xtw.writeStartElement("language");
                xtw.writeCharacters("en");
                xtw.writeEndElement();
                //begin item
                for (i = 0; i < list.size(); i += 4) {
                    xtw.writeStartElement("item");
                    {
                        xtw.writeStartElement("title");
                        xtw.writeCharacters(list.get(i + 3));
                        xtw.writeEndElement();

                        xtw.writeStartElement("link");
                        xtw.writeCharacters(list.get(i + 2));
                        xtw.writeEndElement();

                        xtw.writeStartElement("description");
                        xtw.writeCharacters(list.get(i + 1));
                        xtw.writeEndElement();

                        xtw.writeStartElement("pubDate");
                        xtw.writeCharacters(list.get(i));
                        xtw.writeEndElement();
                    }
                    xtw.writeEndElement();//end item
                }
            }
            xtw.writeEndElement();//end channel
        }
        xtw.writeEndElement();//end rss
        xtw.writeEndDocument();

        xtw.flush();
        xtw.close();
    }
}
